<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
    >
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm">
        <el-form-item label="字典名称" prop="name">
          <el-input v-model="ruleForm.name" />
        </el-form-item>
        <el-form-item label="字典值" prop="value">
          <el-input v-model="ruleForm.value" />
        </el-form-item>
        <el-form-item label="排序号" prop="sort">
          <el-input-number v-model="ruleForm.sort" style="width: 100%" controls-position="right" :min="1" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="ruleForm.remark" type="textarea" />
        </el-form-item>
        <el-form-item>
          <el-button style="float: right" type="primary" @click="submitForm('ruleForm')">确 定</el-button>
          <el-button style="float: right;margin-right: 20px;" @click="close('ruleForm')">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { createdDictionary, updateDictionary } from '@/api/dictionary'
export default {
  name: 'left',
  props: {
    title: {
      type: String,
      default: '新增'
    },
    dialogVisible: {
      type: Boolean,
      default: false
    },
    ruleForm: {
      type: Object,
      // eslint-disable-next-line vue/require-valid-default-prop
      default: {
        name: '',
        value: '',
        sort: '',
        remark: '',
        pid: 0
      }
    }
  },
  data() {
    return {
      rules: {
        name: [
          { required: true, message: '请输入字典名称', trigger: 'blur' }
        ],
        value: [
          { required: true, message: '请输入字典值', trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '请输入排序号', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    console.log('走了created')
  },
  methods: {
    // 关闭弹窗
    close(name) {
      this.$refs[name].resetFields()
      this.$emit('close')
    },
    // 提交弹窗
    submitForm(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          if (this.ruleForm.id) {
            updateDictionary(this.ruleForm).then(res => {
              this.$refs['ruleForm'].resetFields()
              this.$emit('confirm')
            })
          } else {
            createdDictionary(this.ruleForm).then(res => {
              this.$refs['ruleForm'].resetFields()
              this.$emit('confirm')
            }).catch(err => {
              console.log(err)
            })
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
